﻿using System.Text.Json.Serialization;
using BCore.Identity.Users.Caching;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Users.Features.Commands.BatchDelete;

/// <summary>
/// 删除用户
/// </summary>
public class BatchDeleteUserCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 删除的用户ID集合
    /// </summary>
    public required List<Guid> UserIds { get; set; }

    [JsonIgnore]
    public string CacheKey => UsersCacheKey.GetAllCacheKey;

    [JsonIgnore]
    public IEnumerable<string>? Tags => UsersCacheKey.Tags;
}

public class BatchDeleteUserCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<BatchDeleteUserCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(BatchDeleteUserCommand request, CancellationToken cancellationToken)
    {
        var users = await dbContext.Users.Where(x => request.UserIds.Contains(x.Id)).ToListAsync(cancellationToken);
        ExceptionHelper.ThrowIfTrue(users == null || !users.Any(), "数据不存在");

        dbContext.Users.RemoveRange(users!);
        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}
